const fs = require('fs')
const request = require('request')
const path = require('path')
const Bagpipe = require('bagpipe')
let bagpipe = new Bagpipe(20, {
    timeout: 100000
})

const downloadImage = (src, dest, callback) => {
    request.head(src, (err, res, body) => {
        if (err) {
            console.log(err);
            return
        }
        src && request(src).pipe(fs.createWriteStream(dest)).on('close', () => {
            callback && callback(null, dest)
        })
    })
}

const mkdir = function (dir) {
    fs.mkdirSync(`data/${dir}`, { recursive: true }, (err) => {
        // => [Error: EPERM: operation not permitted, mkdir 'C:\']
    });
}

const batchDownload = function (urls, dir) {
    let imageLinks = urls || []
    const getSuffix = str => str.slice(str.lastIndexOf('.'))
    const getName = str => str.substring(str.lastIndexOf('/')+1).split('.')[1]
    mkdir(dir)
    for (let i = 0; i < imageLinks.length; i++) {
        let item = imageLinks[i]
        let destImage = `data/${dir}/${getName(item)}${getSuffix(item)}`
        bagpipe.push(downloadImage, item, destImage, (err, data) => err ? console.log(err) : console.log(path.resolve(data)))
    }
}

module.exports = batchDownload
